// pages/groups/room/edun/edun.js
import { Web_Socket } from "../../../../utils/socket";
import { fnamefixed, Uint8Array2HexStr } from "../../../../utils/util";
import { operationCode } from "../../../../utils/config"
const code = operationCode
const token123 = "token123";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        countEdun: 0,
        countStatues: [0, 0 , 0], //data[0]: 联机；data[1]：绑定；data[2]：锁定
    },

     /**锁定 */
     tapLocking: function(e) {
        const value =  e.detail.value ? 1 : 0;
        const {countEdun, countOnline} = this.data;
        const diff = countEdun - countOnline;
        this.setData({
            checkedLocking: !value
        })
        if (diff !== 0) {
            wx.showModal({
              title: '提示',
              content: `${diff}个设备不在线，请谨慎操作`,
              confirmColor: wx.$theme.color,
              complete: (res) => {
                if (res.confirm) {
                    Object.keys(this.deviceObj).forEach(k => {
                        const message = {
                            deviceKey: k,
                            kvMap: {
                                [value ? code.lockingController : code.unlockingController]: [1],
                                [code.token]: token123
                            }
                        }
                        this.postOthers(message);
                    })
                }
              }
            })
        }
    },

    /**跳到定时锁定 */
    tapScheduleLock: function() {
        const deviceKeys = Object.keys(this.deviceObj);
        const {countEdun, countOnline} = this.data;
        const diff = countEdun - countOnline;
        wx.showModal({
          title: '提示',
          content: `${diff}个设备不在线，请谨慎操作`,
          confirmColor: wx.$theme.color,
          complete: (res) => {
            if (res.confirm) {
                wx.navigateTo({
                  url: `../../../schedule/index`,
                  success(res) {
                      res.eventChannel.emit("deviceKeys", {keys: deviceKeys, countEdun});
                  }
                })
            }
          }
        })
    },

    postOthers(message) {
        this.setData({showLoading: true})
        const {deviceKey, kvMap} = message;
        Object.keys(kvMap).forEach(i => console.log(`edun页面 ${deviceKey}=>请求`, `指令Hex[${parseInt(i).toString(16).toUpperCase().padStart(4, '0')}]`, `值Hex[${Uint8Array2HexStr(kvMap[i], ',')}]`))
        wx.$http.post({url: '/szm/netty/postOthers', data: message}).then(res => {})
    },

    getOnline(message) {
        return wx.$http.post({url: '/szm/netty/online', data: message})
    },

    /**返回状态 */
    [fnamefixed(code.allStatus)](data, deviceKey) {
        // 0x0006：获取联机、绑定、锁定状态
        this.deviceObj[deviceKey] = data.slice(0,3);
        const countStatues = Object.values(this.deviceObj).reduce((acc, cur) => {
            acc[0] + cur[0];
            acc[1] + cur[1];
            acc[2] + cur[2];
            return acc;
        }, [0, 0, 0]);      
        const checkedLocking = this.data.countEdun === countStatues[2];
        this.setData({countStatues, checkedLocking})
        
    },

    /**返回锁定 */
    [fnamefixed(code.lockingController)](data, deviceKey) {
        this.deviceObjLocking[deviceKey] = data[0];
        const countStatues = Object.values(this.deviceObjLocking).reduce((acc, cur) => acc + cur, 0);
        const checkedLocking = this.data.countEdun === countStatues;
        wx.showToast({
            title: '锁定' + countStatues,
          })
        this.setData({checkedLocking})
        // if (checkedLocking) {
        //     wx.showToast({
        //       title: '全部锁定',
        //     })
        // }
    },

    /**返回解锁 */
    [fnamefixed(code.unlockingController)](data, deviceKey) {
        this.deviceObjUnLocking[deviceKey] = data[0];
        const countStatues = Object.values(this.deviceObjUnLocking).reduce((acc, cur) => acc + cur, 0);      
        const checkedLocking = this.data.countEdun === countStatues;
        wx.showToast({
            title: '解锁' + countStatues,
          })
        this.setData({checkedLocking: !checkedLocking})
        // if (checkedLocking) {
        //     wx.showToast({
        //       title: '全部解锁',
        //     })
        // }
    },

    socketOnMessage() {
        wx.$eventEmitter.off('edun');
        wx.$eventEmitter.on('edun', (data) => {
            this.setData({showLoading: false})
            const { kvMap, deviceKey } = data;
            Object.keys(kvMap).forEach(k => {
                const bCode = parseInt(k);
                const fname = fnamefixed(bCode);
                this[fname] && this[fname](kvMap[bCode], deviceKey)
            });
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.socketOnMessage();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        Web_Socket.buildSocket('edun');
        const {placeId} = wx.getStorageSync('place');
        const res = await wx.$http.get({url: `/szm/device/placeId/${placeId}`});
        if (res.code === 0) {
            const room_edun = res.data.filter(cur => cur.roomId > 0);
            if (room_edun.length > 0) {
                this.deviceObj = res.data.reduce((acc, cur) => Object.assign(acc, {[cur.dkey]: [0, 0, 0]}), {});
                this.deviceObjLocking = res.data.reduce((acc, cur) => Object.assign(acc, {[cur.dkey]: 0}), {});
                this.deviceObjUnLocking = res.data.reduce((acc, cur) => Object.assign(acc, {[cur.dkey]: 0}), {});
                const keys = Object.keys(this.deviceObj);
                this.setData({countEdun: keys.length});
                const onlinePromiseList = keys.map( k => {
                    const bindingMessage = {
                        deviceKey: k, 
                        kvMap: {
                            [code.allStatus]: [0x01],
                            [code.token]: token123
                        }
                    }
                    this.postOthers(bindingMessage);
                    return this.getOnline({deviceKey: k});
                });
                Promise.all(onlinePromiseList).then(res => {
                    const countOnline = res.reduce((acc, cur) => acc + cur.data ? 1 : 0, 0)
                    this.setData({countOnline})
                });
            } else {
                this.deviceObj = {}
            }
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})